
import router from './router/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { getToken } from "@/utils/auth"

// permission judge function
function hasPermission (roles, permissionRoles) {

    if (!permissionRoles) return true;

    return permissionRoles.includes(roles)


}
router.beforeEach((to, from, next) => {
    NProgress.start()
    if (to.path == '/login' || to.path == '/forgetPwd' || to.path == '/401') {
        store.commit('SET_ROLES', [])
        next()
    } else {
        if (getToken()) {
            if (store.getters.roles.length == 0) {  //查看路由表,没有的话获取路由表
                store.dispatch('GetUserInfo').then(() => {
                    store.dispatch('GenerateRoutes', store.getters.roles).then(() => {
                        next({ path: to.path })
                        NProgress.done()
                    })
                })
            } else {
                if (hasPermission(store.getters.roles, to.meta.roles)) {  //查看用户有没有权限,没有权限跳转401界面
                    next()
                } else {
                    next({ path: '/401', replace: true, query: { noGoBack: true } })
                }
            }
        } else {
            //没有 token
            next({ path: '/' })
            NProgress.done()
        }
    }
})
router.afterEach(() => {
    NProgress.done(); //完成进度栏
});


